<template>
	<div>
		<a-modal
			:open="props.open"
			:width="
				props.modelInfo && props.modelInfo.width ?
					props.modelInfo.width
				:	'1000px'
			"
			:title="
				props.modelInfo && props.modelInfo.title ?
					props.modelInfo.title
				:	'Basic Modal'
			"
			@ok="handleOk"
			okText="保存"
			:confirmLoading="modelConfig.confirmLoading"
			:destroyOnClose="modelConfig.destroyOnClose"
			@cancel="handleCancel"
		>
			<template #footer>
				<a-button key="back" @click="handleCancel">取消</a-button>
				<a-button
					key="submit"
					type="primary"
					:loading="loading"
					@click="handleOk"
					>保存</a-button
				>
			</template>
			<a-form
				ref="formRef"
				name="EventInfoForm"
				class="ant-advanced-search-form"
				:model="formState"
				@finish="onFinish"
				@finishFailed="onFinishFailed"
				:rules="rulesRef"
				layout="vertical"
			>
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item
							:name="labelMap['title'].name"
							:label="labelMap['title'].label"
						>
							<a-input
								v-model:value="formState.title"
								:placeholder="'请填写' + labelMap['title'].label"
							></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['timeInfo'].name"
							:label="labelMap['timeInfo'].label"
						>
							<a-range-picker
								v-model:value="formState.timeInfo"
								:show-time="{ format: 'HH:mm:ss' }"
								format="YYYY-MM-DD HH:mm:ss"
							/>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['eventLocation'].name"
							:label="labelMap['eventLocation'].label"
						>
							<a-cascader
								v-model:value="formState.eventLocation"
								:options="locationTree"
								:placeholder="'请填写' + labelMap['eventLocation'].label"
								:load-data="loadData"
								:fieldNames="{
									label: 'name',
									value: 'id',
									children: 'children',
								}"
								change-on-select
								@blur="handleChange"
							/>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['feeAmount'].name"
							:label="labelMap['feeAmount'].label"
						>
							<a-input-number
								style="width: 90%"
								v-model:value="formState.feeAmount"
								:placeholder="'请填写' + labelMap['feeAmount'].label"
							></a-input-number>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['participantsCount'].name"
							:label="labelMap['participantsCount'].label"
						>
							<a-input-number
								style="width: 90%"
								v-model:value="formState.participantsCount"
								:placeholder="'请填写' + labelMap['participantsCount'].label"
							></a-input-number>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['images'].name"
							:label="labelMap['images'].label"
						>
							<MyUploadList
								fromSystem="common"
								:fileInfo="fileInfo"
								@customImageRequest="customImageRequest"
								@handleRemove="handleRemove"
							></MyUploadList>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item
							:name="labelMap['description'].name"
							:label="labelMap['description'].label"
						>
							<my-editor
								v-model:content="formState.description"
								@changeContent="
									(content) => changeContent(content, 'description')
								"
							></my-editor>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item
							:name="labelMap['remarks'].name"
							:label="labelMap['remarks'].label"
						>
							<my-editor
								v-model:content="formState.remarks"
								@changeContent="(content) => changeContent(content, 'remarks')"
							></my-editor>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
	</div>
</template>
<script lang="ts" setup>
import { EventInfoDetail } from './eventInfoDetailTs';
import { addOrEditEventInfo, getEventInfoDetail, getLocationTree } from '@/api/eventInfo/eventInfo/eventInfoTs';
import { FormInstance, message } from 'ant-design-vue';
import { ModelInfo } from '../eventInfoListTs';
import dayjs from 'dayjs';

let loading = ref<boolean>(false);

const formRef = ref<FormInstance>();

const labelMap = ref<any>({
	title: { name: 'title', label: '活动标题' },
	description: { name: 'description', label: '活动描述' },
	remarks: { name: 'remarks', label: '注意事项' },
	startTime: { name: 'startTime', label: '活动开始时间' },
	timeInfo: { name: 'timeInfo', label: '活动时间' },
	feeType: { name: 'feeType', label: '费用类型（如AA, 免费等）' },
	feeAmount: { name: 'feeAmount', label: '参加活动费用' },
	participantsCount: { name: 'participantsCount', label: '参与人数' },
	images: { name: 'images', label: '活动封面' },
	eventLocation: { name: 'eventLocation', label: '活动地点' },
});

const rulesRef = reactive({
	title: [
		{
			required: true,
			message: '活动标题不能为空！',
		},
	],
	description: [
		{
			required: true,
			message: '活动描述不能为空！',
		},
	],
	timeInfo: [
		{
			required: true,
			message: '活动时间不能为空！',
			validator: (rule, value) => {
				if (!value || !Array.isArray(value) || value.length === 0) {
					return Promise.reject('活动时间不能为空，且必须是一个非空数组！');
				}
				return Promise.resolve();
			},
		},
	],
	feeType: [
		{
			required: true,
			message: '费用类型（如AA, 免费等）不能为空！',
		},
	],
	images: [
		{
			required: true,
			message: '活动图片不能为空！',
			trigger: 'blur',
		},
	],
	eventLocation: [
		{
			required: true,
			message: '活动地点不能为空！',
			validator: (_rule, value: any[]) => {
				if (!Array.isArray(value) || value.length === 0) {
					return Promise.reject('活动地点必须为一个非空数组！');
				}
				return Promise.resolve();
			},
		},
	],
});

const modelConfig = {
	confirmLoading: true,
	destroyOnClose: true,
};

interface Props {
	open?: boolean;
	modelInfo?: ModelInfo;
}
const props = defineProps<Props>();

let formState = ref<EventInfoDetail>({});

const firstChange = ref<boolean>(true);

const emit = defineEmits(['handleOk', 'handleCancel']);

const handleOk = (): void => {
	loading.value = true;
	if (formRef.value) {
		formRef.value
			.validateFields()
			.then(() => saveEventInfoManager())
			.catch(() => {
				loading.value = false;
			});
	}
};

const handleCancel = (): void => {
	emit('handleCancel', false);
};

const handleChange = (value: any) => {
	if (formState.value?.eventLocation?.length == 3) {
		firstChange.value = false;
		return;
	}
	firstChange.value = false;
	formState.value.eventLocation = [];
};

//保存活动表信息
const saveEventInfoManager = (): void => {
	let method = '';
	if (formState.value.id) {
		method = 'put';
	} else {
		method = 'post';
	}
	let params = {
		id: formState.value.id,
		description: formState.value.description,
		remarks: formState.value.remarks,
		title: formState.value.title,
		startTime:
			formState.value.timeInfo?.length ?
				dayjs(formState.value.timeInfo[0]).format('YYYY-MM-DD HH:mm:ss')
			:	null,
		endTime:
			formState.value.timeInfo?.length ?
				dayjs(formState.value.timeInfo[1]).format('YYYY-MM-DD HH:mm:ss')
			:	null,
		provinceId:
			firstChange.value ?
				formState.value?.provinceId
			:	formState.value.eventLocation?.[0],
		cityId:
			firstChange.value ?
				formState.value?.cityId
			:	formState.value.eventLocation?.[1],
		districtId:
			firstChange.value ?
				formState.value?.districtId
			:	formState.value.eventLocation?.[2],
		eventLocation:
			firstChange.value ?
				formState.value?.districtId
			:	formState.value.eventLocation?.[2],
		feeAmount: formState.value.feeAmount,
		participantsCount: formState.value.participantsCount,
		images: formState.value.images,
	};
	addOrEditEventInfo(method, params)
		.then((res) => {
			if (res.code == '200') {
				message.success((res && res.message) || '保存成功！');
				emit('handleOk', false);
			} else {
				message.error((res && res.message) || '保存失败！');
			}
			formState.value = {};
		})
		.catch((error: any) => {
			message.error(error?.message || '保存失败！');
		})
		.finally(() => {
			loading.value = false;
		});
};

const onFinish = (values: any): void => {
	console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any): void => {
	console.log('Failed:', errorInfo);
};

const changeContent = (content: string, type: string) => {
	switch (type) {
		case 'description':
			formState.value.description = content;
			break;
		case 'remarks':
			formState.value.remarks = content;
			break;
	}
};

const locationTree = ref<any[]>([]);

const getLocationTreeInfo = async (parentId: number): Promise<any> => {
	const {
		data,
		code,
		message: messageInfo,
	} = await getLocationTree({ parentId }).catch((error: any) => {
		message.error(error?.message || '查询失败！');
	});
	if (code == '200') {
		return data;
	} else {
		message.error(messageInfo || '查询失败！');
		return null;
	}
};

const loadData = async (selectedOptions: any[]) => {
	const targetOption = selectedOptions[selectedOptions.length - 1];
	console.log('loadData', selectedOptions, targetOption);
	targetOption.loading = true;
	targetOption.children = await getLocationTreeInfo(targetOption.id);
	if (targetOption.children.length == 0) {
		return;
	}
	targetOption.children.forEach((item: any) => {
		if (targetOption.level == 1) {
			item.isLeaf = false;
			item.level = 2;
		} else {
			item.isLeaf = true;
			item.level = 3;
		}
	});
};

let fileInfo = ref<any[]>([]);

const customImageRequest = (file: any[]) => {
	if (file?.length) {
		formState.value.images = file.map((item) => item.uid).join(',');
	} else {
		formState.value.images = null;
	}
};

const handleRemove = () => {
	formState.value.images = null;
};

const init = async () => {
	fileInfo.value = [];
	if (props.modelInfo) {
		if (props.modelInfo.id) {
			getEventInfoDetail(props.modelInfo.id)
				.then((res) => {
					if (res.code == '200') {
						formState.value = res.data;
						formState.value.timeInfo = [
							res.data?.startTime ? dayjs(res.data.startTime) : null,
							res.data?.endTime ? dayjs(res.data.endTime) : null,
						];
						modelConfig.confirmLoading = false;
						formState.value.eventLocation = [
							res.data?.provinceName,
							res.data?.cityName,
							res.data?.districtName,
						];
						firstChange.value = true;
						console.log(`list ttttttttttttttttttttttt:`, res.data);
						if (formState.value?.imagesList?.length) {
							formState.value?.imagesList.forEach((item: any) => {
								fileInfo.value.push({
									id: item?.id,
									url: item?.preUrl || '',
								});
							});
							console.log(`ddddddddddddddddddddddddddddddd`, fileInfo.value);
						} else {
							fileInfo.value = [];
						}
					} else {
						message.error((res && res.message) || '查询失败！');
					}
				})
				.catch((error: any) => {
					let data = error?.response?.data;
					if (data) {
						message.error(data?.message || '查询失败！');
					}
				});
		} else {
			modelConfig.confirmLoading = false;
			formState.value = {};
			fileInfo.value = [];
			firstChange.value = false;
		}
	}
	locationTree.value = await getLocationTreeInfo(0);
	locationTree.value.forEach((item) => {
		item.isLeaf = false;
		item.level = 1;
	});
};

watch(
	() => props.open,
	(newVal) => {
		if (newVal) {
			init();
		}
	},
	{
		immediate: true,
		deep: true,
	},
);

defineExpose({ handleOk, handleCancel });
</script>
<style lang="scss" scoped></style>
